package com.iocaop.uaa.config;

import lombok.RequiredArgsConstructor;
import org.passay.MessageResolver;
import org.passay.spring.SpringMessageResolver;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

/**
 * MVC配置
 */
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final MessageSource messageSource;

    /**
     * 定义消息解析器bean，使用passay中的解析器，参数需要提供MessageSource
     * 用于passay数据校验 异常消息国际化
     * @return
     */
    @Bean
    public MessageResolver messageResolver(){
        return new SpringMessageResolver(messageSource);
    }

    /**
     * 对jsr380数据校验消息的国际化
     * @return
     */
    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean(){
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource);
        return localValidatorFactoryBean;
    }

    /**
     *静态资源加入到路径
     * @param registry
     */
    @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 读取磁盘文件
      registry.addResourceHandler("/webjars/**")
          // 将磁盘文件解析为以下路径
          .addResourceLocations("/webjars/")
          .resourceChain(false);
      // 设置优先级
      registry.setOrder(1);
    }

    /**
     *路径和url建立映射
     * @param registry
     */
    @Override public void addViewControllers(ViewControllerRegistry registry) {
        // 配置视图 为templates下的login.html  Thymeleaf解析
        registry.addViewController("/login").setViewName("login");
        // 点击退出登录按钮时 跳转到视图index
        registry.addViewController("/perform_logout").setViewName("index");
        // 访问首页时 跳转到视图index
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index").setViewName("index");
        registry.setOrder(HIGHEST_PRECEDENCE);
    }
}
